<template lang="pug">
  v-dialog(v-model="active" persistent=true max-width="70vw" content-class="dlg-mt-off-10vh" scrollable)
    v-card
      v-toolbar
        v-toolbar-title 资产选择
        v-spacer

      v-card-title
        v-container.pb-0
          v-row
            v-text-field(dense, solo, v-model="query" :loading="isQuerying" placeholder="搜索")
          v-row
            v-switch(v-model="showAssets" class="ma-2" label="一般资产" dense hide-details)
            v-switch(v-model="showAssetStocks" class="ma-2" label="批量资产" dense hide-details)
            v-switch(v-model="showBundles" class="ma-2" label="资产组合" dense hide-details)
      v-card-text(style="height: 600px;")
        v-container
          v-row(v-show="showAssets")
            // Assets
            v-list(dense two-line flat subheader width="100%")
              v-subheader 一般资产
              v-list-item-group(multiple v-model="assetsSelected")
                v-list-item(dense v-for="item in assets")
                  template(v-slot:default="{ active, toggle }")
                    v-list-item-action
                      v-checkbox(v-model="active" color="primary" @click="toggleAddAsset")
                    v-list-item-content
                      v-list-item-title {{ item.name }} [{{item.product_model_number}}]
                      v-list-item-subtitle 类别：{{item.category.name}}  |  物品编码：{{item.product_model_number}}  |  序列号：{{ item.sn }}
            // AssetStocks
          v-divider(v-show="showAssetStocks")
          v-row(v-show="showAssetStocks")
            v-list(dense two-line flat subheader width="100%")
              v-subheader 批量资产
              v-list-item-group(multiple v-model="assetStocksSelected")
                v-list-item(dense v-for="item in assetStocks")
                  template(v-slot:default="{ active, toggle }")
                    v-list-item-action
                      v-checkbox(v-model="active" color="primary" @click="toggleAddAsset")
                    v-list-item-content
                      v-list-item-title {{ item.name }}
                      v-list-item-subtitle 类别：{{ item.category.name }} | 库存： {{ item.available_quantity }}
          // Bundles
          v-divider(v-show="showBundles")
          v-row(v-show="showBundles")
            v-subheader 资产组合
            v-expansion-panels
              v-expansion-panel(v-for="bundle in bundles")
                v-expansion-panel-header.py-0
                  v-checkbox.mt-0(dense hide-details :label="bundle.name" v-model="bundlesSelected[bundle.id]" @change="onBundleToggle(bundle)" v-on:click.capture.stop)
                v-expansion-panel-content
                  BundlePicker(:data="bundle", @click="toggleAddAsset")

      v-card-actions
        v-spacer
        v-btn(text color="primary" @click="active = !active") 完成
        // v-btn(text color="primary" @click="addSelectedAssets") 添加
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import {debounce, flatten} from 'lodash'
  import {mapActions, mapGetters, mapMutations, mapState} from 'vuex'
  import BundlePicker from './_bundle_picker'
  import {Asset} from '@/store/modules/types/Asset'
  import {AssetStock} from '@/store/modules/types/AssetStock'
  import {AssetTypes, getLabelByKey, Item, OrderBundle as OrderBundleFormPicker} from '@/store/modules/types/Bundle'
  import {OrderBundle, OrderBundleItem} from '@/store/modules/types/Order'

  function convertBundleItems(items: Item[]): OrderBundleItem[] {
    return items
        .filter(item => item.isSelected === true && item.selected != undefined)
        .map((item: Item) => {
          let selectedItem = item.data[item.selected] as Asset | AssetStock
          let type = getLabelByKey(AssetTypes, selectedItem.type)
          let orderBundleItem: OrderBundleItem = {
            amount: 0,
            order_bundle_id: 0,
            unit_price: 0,
            rentalable_id: selectedItem.id as number,
            rentalable_type: selectedItem.type,
            id: selectedItem.id,
            name: selectedItem.name,
            quantity: item.criteria.quantity
          }
          return orderBundleItem
        })
  }

  function convertBundle(orderBundle: OrderBundleFormPicker): OrderBundle {
    let items = convertBundleItems(orderBundle.items)
    // let amount = get(orderBundle, 'amount', 0)
    let bundle: OrderBundle = {
      bundle_id: orderBundle.id as number,
      name: orderBundle.name,
      items: items,
      amount: orderBundle.amount!
    }
    return bundle
  }

  export default (Vue as VueConstructor<Vue & {}>).extend({
    name: 'order_form_item_picker',
    components: { BundlePicker },
    computed: {
      ...mapState('bundlePicker', ['bundles']),
      ...mapGetters('bundlePicker', ['bundleSelectedAssets']),
    },
    methods: {
      ...mapActions('order', ['retrieveAssets']),
      ...mapMutations('order', ['addAssets', 'addBundle', 'removeBundle']),
      ...mapMutations('bundlePicker', ['updateBundles', 'selectBundle', 'resetBundles']),
      toggle() {
        this.active = !this.active
      },
      toggleAddAsset() {
        setTimeout(() => this.addSelectedAssets(), 500)
      },
      getSelectedAssets() {
        // TODO 特殊处理bundle
        // let { assets, assetStocks }: { assets: Asset[], assetStocks: AssetStock[] } = this.bundleSelectedAssets
        let assets = this.assetsSelected.map(idx => this.assets[idx])
        let assetStocks = this.assetStocksSelected.map(idx => this.assetStocks[idx])
        return { assets, assetStocks }
      },
      addSelectedAssets() {
        this.addAssets(this.getSelectedAssets())
      },
      onBundleToggle(bundle: any) {
        let isSelect = this.bundlesSelected[bundle.id]
        this.selectBundle({ bundle, isSelect })
        if (isSelect) {
          // should convert to bundle
          this.addBundle(convertBundle(bundle))
        } else {
          this.removeBundle((bundle))
        }
        // console.log(`toggle bundle ${bundle.id} is ${isSelect}`)
      },
      reset() {
        this.assets = []
        this.assetStocks = []
        this.assetsSelected = []
        this.assetStocksSelected = []
        this.bundlesSelected = {}
        this.resetBundles()
      },
      prepareData({ data }: any) {
        this.isQuerying = false
        this.assets = data.assets
        this.assetStocks = data.assetStocks
        this.updateBundles(data.bundles)
      }
    },
    watch: {
      query: debounce(function (val) {
        if (val === '') {
          this.prepareData({ data: [] })
          return
        }
        this.isQuerying = true
        this.reset()
        this.retrieveAssets(val).then(this.prepareData)
      }, 800)
    },
    data() {
      return {
        query: '',
        isQuerying: false,
        active: false,
        assets: [],
        assetStocks: [],
        // bundles: [] as Array<any>,
        assetsSelected: [],
        assetStocksSelected: [],
        bundlesSelected: {} as { [key: string]: boolean },
        showAssets: true,
        showAssetStocks: true,
        showBundles: true
      }
    }
  })
</script>

<style>
  .dlg-mt-off-10vh {
    margin-top: -10vh;
  }
</style>